import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import {encrypt} from '@/util/jsencrypt'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref({})
  const login = (loginInfo) =>{
    return new Promise((resolve, reject) =>{
      if(loginInfo.username === 'crocodile' && loginInfo.password === '123456'){
        loginInfo.password =  encrypt(loginInfo.password)
        userInfo.value.username = loginInfo.username
        userInfo.value.account = '鳄鱼杆'
        userInfo.value.token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEyMzQiLCJuYW1lIjoi5rWL6K+V5LqR5a6aIiwic3ViIjoiMTIzNCIsImV4cCI6MTY1NjU5NjY5NH0.h-gX5e7-h4-'
        // 模拟服务器
        setTimeout(() => {
          resolve({
            code: 200,
            msg:  '登录成功'
          })
        }, 1000);
      }
      else{
        resolve({
          code: 401,
          msg: '用户名或密码错误'
      })
      }
    })
  }

  const redirectPath = ref('')
  const toLoginPage = (path) => {
      redirectPath.value = path
  }

  const clearRedirectPath = () => {
    redirectPath.value = ''
  }
  const  logOut = () => {
    return new Promise((resolve, reject) => {
        userInfo.value = {}
        resolve()
    })
  }

  return {
    userInfo,
    redirectPath,
    login,
    logOut,
    toLoginPage,
    clearRedirectPath,
   }
},{
  persist: true,
})
